import { FormSchema } from '@/components/Form';
import { BasicColumn } from '@/components/Table';
import { h } from 'vue';
import { Switch, Tag } from 'ant-design-vue';
import { useMessage } from '@/hooks/web/useMessage';
import { typeItemStatus } from '@/api/system/dict';
import { useDictStoreWithOut } from '@/store/modules/dict';
import { getRandomColor } from '@/utils/common/customColor';

const useDict = useDictStoreWithOut();
const enableList = useDict.getDict('1002');
export const searchFormSchema: FormSchema[] = [
  {
    field: 'name',
    label: '名称',
    component: 'Input',
    colProps: { span: 8 },
  },
  {
    field: 'status',
    label: '状态',
    component: 'Select',
    componentProps: {
      options: enableList,
    },
    colProps: { span: 8 },
  },
];

type CheckedType = boolean | string | number;

export const columns: BasicColumn[] = [
  {
    title: '字典名称',
    dataIndex: 'name',
    width: 200,
  },
  {
    title: '字典值',
    dataIndex: 'value',
    width: 200,
  },
  {
    title: '所属类型',
    dataIndex: 'typeCode',
    width: 200,
    customRender: ({ record }) => {
      return h(
        Tag,
        {
          color: getRandomColor(),
        },
        () => record.typeCode,
      );
    },
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 120,
    customRender: ({ record }) => {
      if (!Reflect.has(record, 'pendingStatus')) {
        record.pendingStatus = false;
      }
      return h(Switch, {
        checked: record.status === '10021001',
        checkedChildren: '启用',
        unCheckedChildren: '停用',
        loading: record.pendingStatus,
        onChange(checked: CheckedType) {
          record.pendingStatus = true;
          const newStatus = checked ? '10021001' : '10021002';
          const { createMessage } = useMessage();
          typeItemStatus(record.id, newStatus)
            .then(() => {
              record.status = newStatus;
              createMessage.success(`已成功修改字典类型状态`);
            })
            .catch(() => {
              createMessage.error('修改字典类型状态失败');
            })
            .finally(() => {
              record.pendingStatus = false;
            });
        },
      });
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
  },
  {
    title: '备注',
    dataIndex: 'remark',
  },
];

export const formTypeItemSchema: FormSchema[] = [
  {
    field: 'id',
    label: '字典id',
    component: 'Input',
    ifShow: false,
  },
  {
    field: 'name',
    label: '字典名称',
    required: true,
    component: 'Input',
  },
  {
    field: 'value',
    label: '字典值',
    required: true,
    component: 'Input',
  },
  {
    field: 'typeCode',
    label: '类型编码',
    component: 'Input',
    ifShow: false,
  },
  {
    field: 'status',
    label: '状态',
    component: 'RadioButtonGroup',
    defaultValue: '10021001',
    componentProps: {
      options: enableList,
    },
  },
  {
    label: '备注',
    field: 'remark',
    component: 'InputTextArea',
  },
];
